package com.tm.aspect;

import com.tm.menum.TransactionType;
import com.tm.transactional.GlobalTransactionManager;
import com.tm.transactional.MyTransaction;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;


/**
 * @author laowu
 * @date 2020/8/22 11:20
 * @desc 自定义切面
 */
@Aspect
@Component
public class GlobalTransactionAspect implements Ordered {

    public int getOrder() {
        return 10000; //需要在Spring事务前面执行
    }

    @Around("@annotation(com.tm.annotation.GlobalTransaction)")
    public void invoke(ProceedingJoinPoint point) {
        // before
        String xid = GlobalTransactionManager.getOrCreateGroup();//获取XID
        // 分支事务
        MyTransaction myTransaction = GlobalTransactionManager.createMyTransaction(xid);
        try {
            point.proceed();
            myTransaction.setTransactionType(TransactionType.commit);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            myTransaction.setTransactionType(TransactionType.rollback);
            throw new RuntimeException(throwable.getMessage());
        } finally {
            // 注册(提交/回滚)
            GlobalTransactionManager.addMyTransaction(myTransaction);
        }
    }
}
